package cn.com.oceansoft.modules.interacts.controller;

import cn.com.oceansoft.application.Constant;
import cn.com.oceansoft.application.common.util.HttpClientUtil;
import cn.com.oceansoft.application.constant.ConfigInfo;
import cn.com.oceansoft.framework.kits.ApiResult;
import cn.com.oceansoft.modules.base.entity.ApiQueryBase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * Created by CS on 2016/10/6.
 * Update by zhul on 2016/11/04
 */
@Controller
@RequestMapping("interacts")
public class InteractsController {

    @Resource
    protected ConfigInfo configInfo;

    @RequestMapping(value = {"index", ""})
    public String main(HttpServletRequest request) {
        return "interacts/index";
    }


    /**
     * 应用中心首页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"goto", ""})
    public String gotoPage(HttpServletRequest request, Model model) throws IOException {
        String gotoUrl = request.getParameter("gotoUrl");
        model.addAttribute("gotoUrl", URLDecoder.decode(gotoUrl, "UTF-8"));
        return "interacts/goto";
    }

    /**
     * 应用中心-实时路况
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"tmc"})
    public String gotoInteractsRealtimeTraffic(HttpServletRequest request) {
        return "interacts/realtimeTraffic";
    }


    /**
     * 应用中心-地图导航
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"mapnav"})
    public String gotoInteractsMapNavigation(HttpServletRequest request) {
        return "interacts/mapNavigation";
    }


    /**
     * 应用中心-地图导航
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "mapnav/page", method = GET)
    public Object gotoInteractsMapNavigationSearchUnit(HttpServletRequest request) {
        ApiResult apiResult = null;
        try {
            String ps = request.getParameter("ps");
            String pi = request.getParameter("pi");
            String deptname = request.getParameter("deptname");
            String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "depts/page",
                    "ps", ps,
                    "pi", pi,
                    "q_dept_name_s_lk", deptname);
            apiResult = JSONObject.parseObject(result, ApiResult.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return apiResult;
        }
    }

    /**
     * 获取地图导航部门
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "mapnav/dept/{id}", method = {GET, POST})
    public Object getMapNavDetail(@PathVariable("id") String id, HttpServletRequest request, ModelMap model) {
        ApiResult apiResult = null;
        String url = configInfo.getMsHostUrl() + "depts/" + id;
        String result = HttpClientUtil.doGet(url);
        //model.addAttribute("json", JSONObject.parseObject(result));
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }


    /**
     * 应用中心首页-场景导航
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"scenenav", ""})
    public String SceneNavigation(HttpServletRequest request) {
        return "interacts/scenenav";
    }


    /**
     * 应用中心-表格下载
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"billresource"})
    public String gotoInteractsBillResource(HttpServletRequest request, Model model) {
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/matters/pccs");
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        model.addAttribute("pcc", apiResult.getData());
        return "interacts/billresource";
    }

    /**
     * 应用中心-表格下载列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "billresource/page", method = GET)
    public String findBillResources(HttpServletRequest request, ApiQueryBase query, Model model) throws IOException {

//        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "interacts/billresource/page",
//                "ps", query.getPs(),
//                "pi", query.getPi(),
//                "where", URLEncoder.encode(query.getWhere(), "utf-8"),
//                "kw", URLEncoder.encode(query.getWhere(), "utf-8")
//        );

        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "interacts/billresource/page", request.getParameterMap(), "UTF-8");
        //String result = HttpClientUtil.doPostString(configInfo.getMsHostUrl() + "interacts/billresource/page", query);

        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        model.addAttribute("result", apiResult);

        return "interacts/billresource_list";
    }

    /**
     * 应用中心-失物招领
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"lostproperty"})
    public String lostproperty(HttpServletRequest request) {
        return "interacts/lostProperty";
    }

    /**
     * 应用中心-失物招领列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "lostproperty/page", method = GET)
    public Object findLostproperty(HttpServletRequest request) {
        ApiResult apiResult = null;
        String ps = request.getParameter("ps");
        String pi = request.getParameter("pi");
        String lostname = request.getParameter("lostname");
        String orgname = request.getParameter("orgname");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String infotype = request.getParameter("infotype");

        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "interacts/lostproperty/page",
                "ps", ps,
                "pi", pi,
                "lostname", lostname,
                "orgname", orgname,
                "starttime", starttime,
                "endtime", endtime,
                "infotype", infotype
        );
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * 获取获取失物招领明细信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "lostproperty/{id}", method = {GET})
    public Object getLostPropertyDetail(@PathVariable("id") String id, HttpServletRequest request, ModelMap model) {
        ApiResult apiResult = null;
        String url = configInfo.getMsHostUrl() + "interacts/lostproperty/" + id;
        String result = HttpClientUtil.doGet(url);
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;

    }

    /**
     * 应用中心-举报12389协议
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"12389protocol"})
    public String main12389protocol(HttpServletRequest request, Model model) {
        return "interacts/main12389protocol";
    }

    /**
     * 应用中心-举报12389
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"12389"})
    public String main12389(HttpServletRequest request, Model model) {
        return "interacts/main12389";
    }

    /**
     * 应用中心-举报12389提交
     *
     * @param request
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "post12389", method = POST)
    public ApiResult post12389(HttpServletRequest request, @RequestBody Map map) {

        System.out.println(JSON.toJSONString(map));
        String result = HttpClientUtil.doPostString(configInfo.getMsHostUrl() + "/interacts/12389", map);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
        //return new ApiResult(true, 10200, "", null);
    }

    @ResponseBody
    @RequestMapping(value = "12389/page", method = GET)
    public ApiResult page12389(HttpServletRequest request) {
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/interacts/12389/page", request.getParameterMap(), "UTF-8");
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    @ResponseBody
    @RequestMapping(value = "12389/{id}", method = GET)
    public ApiResult detail12389(@PathVariable String id, HttpServletRequest request) {
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/interacts/12389/" + id);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);

        return apiResult;
    }

    /**
     * 附件上传，返回保存成功后的guid
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "12389/att", method = POST)
    public ApiResult post12389att(MultipartHttpServletRequest request) {


        MultipartFile mp = request.getFile("materialFile");
        String orifileName = mp.getOriginalFilename();

        File file = null;
        try {
            file = new File(URLEncoder.encode(orifileName, "utf-8"));
            FileUtils.writeByteArrayToFile(file, mp.getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = HttpClientUtil.uploadFile(configInfo.getMsHostUrl() + "/interacts/12389/att", file);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        file.delete();
//        JSONObject json = new JSONObject();
//        json.put("fileName", mp.getOriginalFilename());
//        json.put("guid", apiResult.getData());
        return ApiResult.succ(apiResult);
    }

    /**
     * 应用中心-12389附件删除
     */

    @ResponseBody
    @RequestMapping(value = "12389/att/{id}", method = DELETE)
    public ApiResult delete12389Att(@PathVariable String id, HttpServletRequest request) {
        String result = null;

        result = HttpClientUtil.doDel(configInfo.getMsHostUrl() + "/interacts/12389/att/" + id);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }


    /**
     * 应用中心-线索举报协议
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"reportprotocol"})
    public String reportProtocol(HttpServletRequest request, Model model) {
        return "interacts/reportprotocol";
    }

    /**
     * 应用中心-线索举报
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"report"})
    public String report(HttpServletRequest request, Model model) {
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "/depts/sj");
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        model.addAttribute("depts", apiResult.getData());
        return "interacts/report";
    }

    /**
     * 应用中心-线索举报提交
     *
     * @param request
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "postreport", method = POST)
    public ApiResult postReport(HttpServletRequest request, @RequestBody Map map) {

        System.out.println(JSON.toJSONString(map));
        Map mp_current_member = (Map) request.getSession().getAttribute(Constant.CURRENT_MEMBER);
        map.put("userguid", mp_current_member.get("guid"));
        map.put("username", mp_current_member.get("realName"));
        map.put("currentMemberMobile", mp_current_member.get("acountId"));
        String result = HttpClientUtil.doPostString(configInfo.getMsHostUrl() + "/interacts/report", map);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * 图片附件上传，返回保存成功后的guid
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "report/att/{sourcetype}", method = POST)
    public ApiResult postReportAtt(@PathVariable("sourcetype") String sourcetype, MultipartHttpServletRequest request) {
        String requestUrl;
        MultipartFile mp;

        if (sourcetype.equals("image")) {
            requestUrl = "/interacts/report/att/image";
            mp = request.getFile("materialImage");
        } else {
            requestUrl = "/interacts/report/att/video";
            mp = request.getFile("materialVideo");
        }

        String orifileName = mp.getOriginalFilename();
        String enCodeName = null;
        try {
            enCodeName = URLEncoder.encode(orifileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        File file = new File(enCodeName);
        try {
            FileUtils.writeByteArrayToFile(file, mp.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result = HttpClientUtil.uploadFile(configInfo.getMsHostUrl() + requestUrl, file);
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        file.delete();

        return ApiResult.succ(apiResult);
    }


    /**
     * 应用中心-线索举报附件删除
     */

    @ResponseBody
    @RequestMapping(value = "report/att/{id}", method = DELETE)
    public ApiResult deleteReportAtt(@PathVariable String id, HttpServletRequest request) {
        String result = null;

        try {
            result = HttpClientUtil.doDel(configInfo.getMsHostUrl() + "/interacts/report/att/" + id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApiResult apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * 应用中心-寻人寻亲
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"lostperson"})
    public String lostperson(HttpServletRequest request) {
        return "interacts/missingPerson";
    }

    /**
     * 应用中心-寻人寻亲列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "lostperson/page", method = GET)
    public Object findLostperson(ApiQueryBase query, HttpServletRequest request) {
        ApiResult apiResult = null;
        String ps = request.getParameter("ps");
        String pi = request.getParameter("pi");
        String lostpersonname = request.getParameter("lostpersonname");
        String orgname = request.getParameter("orgname");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String losttype = request.getParameter("losttype");
        String result = HttpClientUtil.doGet(configInfo.getMsHostUrl() + "interacts/lostperson/page",
                "ps", ps,
                "pi", pi,
                "lostpersonname", lostpersonname,
                "orgname", orgname,
                "starttime", starttime,
                "endtime", endtime,
                "losttype", losttype
        );
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;
    }

    /**
     * 获取获取寻人寻亲细信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "lostperson/{id}", method = {GET})
    public Object getLostPersonDetail(@PathVariable("id") String id, HttpServletRequest request, ModelMap model) {
        ApiResult apiResult = null;
        String url = configInfo.getMsHostUrl() + "interacts/lostperson/" + id;
        String result = HttpClientUtil.doGet(url);
        apiResult = JSONObject.parseObject(result, ApiResult.class);
        return apiResult;

    }

}
